package www.wen.com.common.lib.base.fragment

import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.dylanc.loadingstateview.LoadingStateView
import com.dylanc.loadingstateview.ViewType
import com.gyf.immersionbar.ImmersionBar
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import www.wen.com.common.BR
import www.wen.com.common.R
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter.Companion.IS_FULL_UNPACK
import www.wen.com.common.lib.util.DisplayUtil
import www.wen.com.common.lib.util.KeyboardUtils
import www.wen.com.common.lib.view.OnMultipleClickListener


/**
 * @author WEN
 * @Description: Fragment基类，封装了通用标题栏
 * @date 2020/11/25 17:49
 */
abstract class BaseVMFragment<K : ViewDataBinding> : Fragment(), LoadingStateView.OnReloadListener {

    /**
     * Fragment 是否可以见,只适用viewpager
     */
    var mFragmentIsVisible = false

    private var mIsInit = false

    var mLoadingHelper: LoadingStateView? = null

    open val mIsAddShadow = true

    protected lateinit var dataBinding: K

    protected lateinit var mRootView: View

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {

        dataBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)

        dataBinding.lifecycleOwner = this
        dataBinding.setVariable(BR.listener, mOnMultipleClickListener)

        //是否启用快捷标题栏
        isUseLoadingHelper()

        mRootView = mLoadingHelper?.decorView ?: dataBinding.root

        addShadowImage()

        return mRootView
    }

    /**
     * 如果页面使用LoadingStateView作为标题返回，并且mIsAddShadow为true的情况，布局容器为LinearLayout或FrameLayout在标题下方添加阴影图片
     */
    open fun addShadowImage() {
        if (mIsAddShadow && isEnableLoadingHelper()) {
            val shadowImageView = ImageView(requireContext())
            shadowImageView.scaleType = ImageView.ScaleType.FIT_XY
            shadowImageView.setImageResource(R.drawable.actionbar_shadow_down)
            when (mRootView) {
                is LinearLayout -> {
                    if (isEnableLoadingHelper()) {
                        when (val viewGroup =
                            ((mRootView as LinearLayout).getChildAt(1) as FrameLayout).getChildAt(0)) {
                            is ConstraintLayout -> {
                                shadowImageView.id = R.id.ivShadow
                                val shadowImageViewParams: ConstraintLayout.LayoutParams =
                                    ConstraintLayout.LayoutParams(
                                        ConstraintLayout.LayoutParams.MATCH_CONSTRAINT,
                                        DisplayUtil.dip2px(5f).toInt()
                                    )
                                shadowImageViewParams.startToStart =
                                    ConstraintLayout.LayoutParams.PARENT_ID
                                shadowImageViewParams.endToEnd =
                                    ConstraintLayout.LayoutParams.PARENT_ID
                                shadowImageViewParams.topToTop =
                                    ConstraintLayout.LayoutParams.PARENT_ID
                                shadowImageView.layoutParams = shadowImageViewParams
                                viewGroup.addView(shadowImageView)
                            }
                            is FrameLayout -> {
                                viewGroup.addView(
                                    shadowImageView, FrameLayout.LayoutParams(
                                        FrameLayout.LayoutParams.MATCH_PARENT,
                                        DisplayUtil.dip2px(5f).toInt(),
                                        Gravity.TOP
                                    )
                                )
                            }
                        }
                    }
                }
            }
        }
    }

    private fun isUseLoadingHelper() {
        if (isEnableLoadingHelper()) {
            mLoadingHelper = getLoadingHelper().apply {
                configurationLoadingHelper(this)
                setOnReloadListener(this@BaseVMFragment)
            }
        }
    }

    /**
     * Fragment可见监听
     */
    open fun onVisible() {
        statusBarInitialize()
    }

    /**
     * Fragment不可见监听
     */
    open fun onInVisible() {}

    /**
     * 状态栏文字颜色设置
     */
    open fun statusBarDarkFont() = true

    /**
     * 状态栏设置
     */
    private fun statusBarInitialize() {
        if (activity != null) {
            ImmersionBar.with(requireActivity()).statusBarDarkFont(statusBarDarkFont()).init()
        }
    }

    override fun onReload() {}

    open fun getLoadingHelper(): LoadingStateView {
        return LoadingStateView(dataBinding.root)
    }

    open fun configurationLoadingHelper(loadingHelper: LoadingStateView): LoadingStateView {
        loadingHelper.register(ViewType.TITLE, getTitleBarUniversalAdapter())
        loadingHelper.setDecorHeader(ViewType.TITLE)
        return loadingHelper
    }

    open fun getTitleBarUniversalAdapter(): LoadingStateView.ViewDelegate<*> =
        TitleBarUniversalAdapter(
            requireActivity(),
            getString(R.string.logging_in),
            action = ::titleAction
        )

    open fun isEnableLoadingHelper() = false

    open fun titleAction(v: View) {
        when (v.id) {
            R.id.tvRight,
            R.id.ivRight,
            -> {
                actionRight()
            }
            R.id.tvLeft,
            R.id.ivLeft,
            -> {
                actionLeft()
            }
        }
    }

    open fun actionRight() {}

    open fun actionLeft() {
        findNavController().navigateUp()
    }

    override fun onResume() {
        super.onResume()
        mFragmentIsVisible = true
        if (!mIsInit) {
            lazyInitView()
            mIsInit = true
        }
        onVisible()
    }

    override fun onPause() {
        super.onPause()
        mFragmentIsVisible = false
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            onVisible()
        } else {
            onInVisible()
        }
    }

    abstract fun lazyInitView()

    abstract fun getLayoutId(): Int

    override fun onDestroy() {
        super.onDestroy()
        KeyboardUtils.hideSoftInput(requireActivity())
    }

    /**
     * 1秒内防重复点击
     */
    private val mOnMultipleClickListener = object : OnMultipleClickListener() {
        override fun onIClick(v: View) {
            this@BaseVMFragment.onClick(v)
        }
    }

    open fun onClick(v: View) {}

    /**
     * 接收系统相册、相机的图片回调
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            PictureConfig.CHOOSE_REQUEST -> {
                PictureSelector.obtainMultipleResult(data)
            }
        }
    }

}